package com.wenx.stack;

import java.util.Arrays;

/**
 * 使用数组实现栈
 * 自己实现一个栈，要求这个栈具有push()、pop()（返回栈顶元素并出栈）、peek() （返回栈顶元素不出栈）、isEmpty()、size()这些基本的方法。
 * 提示：每次入栈之前先判断栈的容量是否够用，如果不够用就用Arrays.copyOf()进行扩容；
 * Created by wenx on 2019-10-11 14:39
 */
public class MyStack {

    //存元素的数组
    private Object[] elements;

    //栈大小
    int capacity;

    //每次扩容的大小
    private static final int GROW_FACTOR = 2;

    //当前入栈元素的数量
    private int count;

    public MyStack() {
        //初始化大小
        capacity = 8;
        elements = new Object[capacity];
        count = 0;
    }

    public boolean push(Object e) {
        if(count == capacity) {
            //需要扩容
            System.out.println("扩容");
            int newcapacity = capacity * GROW_FACTOR;
            elements = Arrays.copyOf(elements,newcapacity);
            capacity = newcapacity;
        }
        System.out.println("入栈"+count);
        elements[count++] = e;
        return true;
    }

    public Object pop() {
        if(count == 0) {
            System.out.println("空栈");
            return null;
        }
        --count;
        Object top = elements[count];
        System.out.println("出栈 = " + top);
        elements[count] = null;
        return top;
    }

    public Object peek() {
        if(count == 0) {
            System.out.println("空栈");
            return null;
        }
        int topPosition = count - 1;
        Object top = elements[topPosition];
        System.out.println("栈顶元素不出栈 = " + top);
        return top;
    }

    public boolean isEmpty() {
        return count == 0;
    }

    public int size() {
        return count;
    }

}